<?php

namespace App\Http\Controllers\Api\CMS;

use App\Http\Resources\NavigationResource;
use App\Models\CMS\Category;
use App\Models\CMS\Content;
use App\Models\CMS\Navigation;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class NavigationController extends Controller
{

    const MESSAGES_ARR = [
        'point_url.required' => 'url必填',
        'point_category_id.required' => '分类必填',
        'point_content_id.required' => '内容必填',
    ];

    /**
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $type = $request->get('type', null);
        $navigation = Navigation::query()->when($type, function ($queryString) use ($type) {
            $queryString->where('type', $type);
        })->with('category', 'content', 'parent')->orderByDesc('id')->get();
        return $this->navigation($navigation);
    }

    /**
     * @param Request $request
     * @return NavigationResource|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function store(Request $request)
    {
        $data = $request->all();
        $model = new Navigation();
        $model->fill($data);
        if ($data['point_category_id']) {
            $model->point_category_id = end($data['point_category_id']);
            $model->point_category_path = implode("-", $data['point_category_id']);
        }
        $validate = $this->validateData($data, $model);
        $validator = $validate['validator'];
        $model = $validate['model'];
        if ($validator->fails()) {
            return response($validator->errors(), 422);
        }
        $model->save();
        return new NavigationResource($model);
    }

    /**
     * @param $id
     * @return NavigationResource
     */
    public function show($id)
    {
        $model = $this->findModel($id);
        return new NavigationResource($model);
    }

    /**
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */

    /**
     * @param $navigations
     * @param int $parent_id
     * @return array
     */
    function navigation($navigations, $parent_id = 0)
    {
        $arr = array();
        foreach ($navigations as $navigation => $values) {
            if ($values['parent_id'] == $parent_id) {
                $values['children'] = $this->navigation($navigations, $values['id']);
                $arr[] = $values;
            }
        }
        return $arr;
    }

    /**
     * @param $navId
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($navId)
    {
        $model = Navigation::query()->where('id', $navId)->first();
        $model->delete();
        $this->deleteSonNavigation($navId);
        return response()->json(['删除成功！']);
    }


    /**
     * @param Request $request
     * @param $navId
     * @return NavigationResource|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function update(Request $request, $navId)
    {
        $data = $request->all();
        $model = $this->findModel($navId);
        $model->fill($data);
        if ($data['point_category_id']) {
            $model->point_category_id = end($data['point_category_id']);
            $model->point_category_path = implode("-", $data['point_category_id']);
        }
        $validate = $this->validateData($data, $model);
        $validator = $validate['validator'];
        $model = $validate['model'];

        if ($validator->fails()) {
            return response($validator->errors(), 422);
        }
        $model->save();
        return new NavigationResource($model);
    }


    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|null|object
     */
    public function findModel($id)
    {
        $model = Navigation::query()->with('content')->where('id', $id)->first();
        return $model;
    }


    /**
     * @param $data
     * @param $model
     * @return array
     */
    protected function validateData($data, $model)
    {
        switch ($data['point_type']) {
            case 0:         //单页
                $validator = Validator::make($data, [
                    'point_category_id' => 'required',
                    'point_content_id' => 'required'
                ], self::MESSAGES_ARR);
                $model->point_url = 'content/' . $model->point_content_id;
                break;
            case 1:         //列表
                $validator = Validator::make($data, [
                    'point_category_id' => 'required'
                ], self::MESSAGES_ARR);
                //$model->point_category_id=null;
                $model->point_url = 'list/' . $model->point_category_id;
                $model->point_content_id = 0;

                break;
            case 2:         //外链
                $validator = Validator::make($data, [
                    'point_url' => 'required'
                ], self::MESSAGES_ARR);
                $model->point_content_id = 0;
                $model->point_category_id = 0;
                break;
            case 3:         //单页
                $validator = Validator::make($data, [
                    'point_category_id' => 'required',
                    'point_content_id' => 'required'
                ], self::MESSAGES_ARR);
                $content = Content::query()->with('content_detail')
                    ->where('id',$data['point_content_id'])->first();
                $model->point_url = $content->content_detail->asset->path ;
                break;
            default:      //无  不加会报undefined
                $validator = Validator::make($data, [
                ], self::MESSAGES_ARR);
                $model->point_url = null;
                $model->point_content_id = 0;
                $model->point_category_id = 0;
        }
        return ['validator' => $validator, 'model' => $model];
    }

    /**
     * @param $parent_id
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function getChild($parent_id)
    {
        $model = Navigation::query()->where('parent_id', $parent_id)->get();
        return NavigationResource::collection($model);
    }


    /**
     * 删除该栏目下的所有子导航
     * @param $id
     */
    public function deleteSonNavigation($id)
    {
        $models = Navigation::query()->where('parent_id', $id)->get();
        if ($models) {
            foreach ($models as $model) {
                $this->deleteSonNavigation($model->id);
                $model->delete();
            }
        }
    }
}
